package com.wx.common.file;

import java.io.*;
import java.nio.charset.StandardCharsets;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public  class MsgUtils {

//    处理路径
    private static File getFile(String filePath){
        try {
            filePath=new String(filePath.getBytes(StandardCharsets.ISO_8859_1),StandardCharsets.UTF_8);
            File file = new File(filePath);
            if (!file.exists()) {
                file.createNewFile();
            }
            return file;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
//    处理集合
    private static List<String[]> dealList(List<String[]> list0,String old,String rep){
        List<String[]> list1=new ArrayList<>();
        List<String> list2=new ArrayList<>();
        for (String[] strings : list0) {
            for (String string : strings) {
               list2.add(string.replace(old,rep));
            }
            String[] strings1 = list2.toArray(new String[list2.size()]);
            list2=new ArrayList<String>();
            list1.add(strings1);
        }
        return list1;
    }
//    写入
public static void OutputMsg(String filePath, List<String[]> list) {
        OutputMsg(filePath,list,0);
}

    public static void OutputMsg(String filePath, List<String[]> list,int i){
        try {
            File file = getFile(filePath);
            if(file.length()==0||i==1){
                file.delete();
                file.createNewFile();
            BufferedWriter bw = new BufferedWriter(new FileWriter(file));
            List<String[]> list2 = dealList(list,",", "$!");
            for (String[] strings : list2) {
                bw.write(Arrays.toString(strings)+"#");
            }
            bw.flush();
            bw.close();
            }

        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
//    读取
    public static List<String[]> InputMsg(String filePath){
        try {
            File file = getFile(filePath);
            BufferedReader br=new BufferedReader(new FileReader(file));
            String a;
            StringBuilder sb=new StringBuilder();
            while ((a=br.readLine())!=null) {
                sb.append(a);
            }
            String[] split = sb.toString().split("#");
            List<String[]> lists=new ArrayList<>();
            for (String s : split) {
                String[] split1 = s.substring(1, s.length() - 1).split(",");
                lists.add(split1);
            }
            List<String[]> dealList = dealList(lists, "$!", ",");
            br.close();
            return dealList;
        }catch (Exception e){
            throw new RuntimeException(e.getMessage());
        }
    }
}
